﻿/// <remarks>
///系统名称            :   ITALKI 翻译系统
///模块名称            :   Translate
///文件代码            :   
///功能概述            :   
///创建人              :   Snail
///创建日期            :   2008.08.07
///版本号              :   1.0.0.0
///----------< 修改履历 >---------------------------------------------------------------
///修改日期          修改人              修改内容                           版本号
///------------------------------------------------------------------------------------
/// (C) 2007-2008 上海微语信息技术有限公司  版权所有。保留所有权利。
///------------------------------------------------------------------------------------
///</remarks>
namespace Web.Control.WWW.translate
{
    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Xml;
    using Lx.Web.Common.ControlsUI;
    using BLF.WWW_WWW.translate;
    using Lx.Web.Common.UI;
    using Model.WWW_WWW.translate;
    using System.Text.RegularExpressions;

    /// <summary>
    /// 页面类。
    /// </summary>
    public partial class translate : BaseControl
    {
        protected string LangName;
        protected TranslateItem SingleTranslate;
        protected List<TranslateModel> SingleTranslateModels;
        protected List<TranslateComment> SingleTranslateComments;
        protected TranslateMember CurrentMember;
        protected int ContentCount;
        protected int PageIndex = 1;
        protected int PageSize = 20;

        //是否已有最佳答案
        protected bool HasGoodFlag;

        //是否当前会员已经对该词条进行了翻译
        protected bool IsTranslated;


        /// <summary>
        /// 页面装载事件。
        /// </summary>
        ///修改日期          修改人              修改内容                           版本号
        ///2008.08.07		 Snail				 创建该方法                         1.0.0.0
        protected override void OnLoad(EventArgs e) {
            //判断是否登录
            if (HttpContext.Current.User.Identity.Name == "") {
                Response.Redirect(WWWHost + "/User/login.htm?ReturnUrl=" + Request.Url.AbsoluteUri.Split('?')[0]);
            }

            //如果未传递正确的语言参数则跳转到translate首页
            if (string.IsNullOrEmpty(Request.QueryString["lang"])) {
                Response.Redirect("/translate/default.htm");
            }

            //检查语言参数是否匹配。
            XmlDocument xDoc = new XmlDocument();
            try {
                xDoc.Load(string.Format(Server.MapPath("LangSet/LangSet_{0}.xml"), Globals.Language));
            } catch {
                xDoc.Load(string.Format(Server.MapPath("LangSet/LangSet_en-us.xml"), Globals.Language));
            }

            XmlNodeList xnl = xDoc.SelectNodes("//LangSet/Lang");
            if (xnl != null) {
                bool paramOK = false;
                foreach (XmlNode xn in xnl) {
                    if (xn.ChildNodes[0].InnerText == Request.QueryString["lang"]) {
                        LangName = xn.ChildNodes[1].InnerText;
                        paramOK = true;
                    }
                }
                if (!paramOK)
                    Response.Redirect("/translate/default.htm");
            } else
                Response.Redirect("/translate/default.htm");


            //判断其是否为翻译成员
            CurrentMember = Translate.GetTranslateMember(HttpContext.Current.User.Identity.Name);

            //删除翻译条目
            string deleteID;
            if (!string.IsNullOrEmpty(deleteID = Request.QueryString["delete"])) {
                //判断是否为管理员
                if (CurrentMember != null && CurrentMember.IsAdmin) {
                    Response.Write("<script>alert('delete " + (Translate.DeleteTranslateItem(deleteID) > 0 ? "succed" : "failed") + "!');window.location.href='/translate/translate.htm?lang=" + Request.QueryString["lang"] + "';</script>");
                } else {
                    Response.Redirect("/translate/default.htm");
                }
            }

            //标记最佳答案
            string goodID, itemNo;
            if (!string.IsNullOrEmpty(goodID = Request.QueryString["good"])) {
                if (!string.IsNullOrEmpty(itemNo = Request.QueryString["id"])) {
                    //判断是否为管理员
                    if (CurrentMember != null && CurrentMember.IsAdmin) {
                        Response.Write("<script>alert('update " + (Translate.SetGoodFlag(goodID) > 0 ? "succed" : "failed") +
                                       "!');window.location.href='/translate/translate.htm?lang=" +
                                       Request.QueryString["lang"] + "&id=" + itemNo + "';</script>");
                    } else {
                        Response.Redirect("/translate/default.htm");
                    }
                }
            }

            //提交翻译内容
            if (!string.IsNullOrEmpty(Request.Form["texta_content"])) {
                if (CurrentMember == null)
                    Response.Redirect("/translate/join.htm?ReturnUrl=" + HttpUtility.UrlEncode("/translate/translate.htm?lang=" + Request.QueryString["lang"] + "&id=" + Request.Form["hide_itemno"] + "#text_anchor"));
                Translate.AddTranslateContent(Request.Form["hide_itemno"], Request.Form["texta_content"].Replace("\r", "").Replace("\n", ""),
                                              Request.QueryString["lang"], 0, false, HttpContext.Current.User.Identity.Name);
                Response.Redirect("/translate/translate.htm?lang=" + Request.QueryString["lang"] + "&id=" + Request.Form["hide_itemno"] + "#text_anchor");
            }

            //显示指定ID的翻译条目。
            if (!string.IsNullOrEmpty(Request.QueryString["id"])) {
                if (!string.IsNullOrEmpty(Request["p"])) {
                    if (Request["p"] == "l") {
                        PageIndex = 999;
                    } else {
                        int.TryParse(Request["p"], out PageIndex);
                        if (PageIndex == 0) {
                            PageIndex = 1;
                        }
                    }
                }
                string id = Request.QueryString["id"];
                int jsymbol = id.IndexOf('#');
                if(jsymbol >= 0)
                    id = id.Substring(0, jsymbol);

                SingleTranslate = Translate.GetTranslatesByLanguage(id, Request.QueryString["lang"], (PageIndex - 1) * PageSize, PageSize,
                                                  out SingleTranslateModels, out ContentCount);
                for (int i = 0; i < SingleTranslateModels.Count; i++) {
                    if (SingleTranslateModels[i].MemberNo == HttpContext.Current.User.Identity.Name)
                        IsTranslated = true;
                    if (SingleTranslateModels[i].GoodFlag) {
                        HasGoodFlag = true;
                        break;
                    }
                }
                return;
            }

            //随机选出一条翻译条目。
            SingleTranslate = Translate.GetTranslateRandom(Request.QueryString["lang"], out SingleTranslateModels, out SingleTranslateComments, out ContentCount);
            for (int i = 0; i < SingleTranslateModels.Count; i++) {
                if (SingleTranslateModels[i].MemberNo == HttpContext.Current.User.Identity.Name)
                    IsTranslated = true;
                if (SingleTranslateModels[i].GoodFlag) {
                    HasGoodFlag = true;
                    break;
                }
            }


            base.OnInit(e);
        }

        /// <summary>
        /// 高亮带有{数字}、或HTML代码的文本。
        /// </summary>
        /// <param name="text">原文。</param>
        /// <returns>加色后的文本。</returns>
        ///2008.08.07		 Snail				 创建该方法                         1.0.0.0
        protected string HighLightCode(string text) {
            Regex regex = new Regex(@"<(\S*?)[^>]*>");
            MatchCollection mc = regex.Matches(text);
            text = regex.Replace(text, new MatchEvaluator(replaceHTML));



            regex = new Regex(@"{\d+}");
            mc = regex.Matches(text);
            for (int i = 0; i < mc.Count; i++)
                text = text.Replace(mc[i].Value, string.Format("<font color=\"red\">{0}</font>", mc[i].Value));

            return text;
        }

        /// <summary>
        /// 替换HTMLCode
        /// </summary>
        /// <returns>替换后的文本</returns>
        ///2008.08.13		 Snail				 创建该方法                         1.0.0.0
        private string replaceHTML(Match match) {
            return "<font color=\"red\">" + match.Value.Replace("<", "&lt;").Replace(">", "&gt;") + "</font>";
        }
    }
}